<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['comprehensive:ranking:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['comprehensive:ranking:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comprehensive:ranking:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['comprehensive:ranking:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="uploadVClick">根据excel导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-dialog title="导入" :visible.sync="uploadV" width="1000px" append-to-body>
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-upload center class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed" action=""
          :file-list="fileList" :on-change="fileChoose">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
          <!-- <div class="el-upload__tip" slot="tip">
            只能上传xlsx/xls文件
            <el-link @click="downloadMode" type="primary" size="mini">下载模板</el-link>
          </div> -->
        </el-upload>
      </el-row>

      <el-table border :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)" :stripe="true"
        :current-page.sync="currentPage" max-height="550" style="width: 100%">
        <el-table-column prop="stuNo" label="学号" width="180">
        </el-table-column>
        <el-table-column prop="avgCredit" label="平均学分绩">
        </el-table-column>
        <el-table-column prop="ranking" label="排名">
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 15, 20]"
          :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doImport()">导 入</el-button>
      </span>
    </el-dialog>

    <el-table v-loading="loading" :data="rankingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="#" align="center" prop="id" />
      <el-table-column label="学号" align="center" prop="stuNo" />
      <!-- <el-table-column label="所选课程总学分" align="center" prop="courseCredit" />
      <el-table-column label="所得总学分" align="center" prop="totalCredit" />
      <el-table-column label="总成绩" align="center" prop="totalScore" />
      <el-table-column label="课程数" align="center" prop="courseNum" />
      <el-table-column label="平均分" align="center" prop="avgScore" /> -->
      <el-table-column label="平均学分绩" align="center" prop="avgCredit" />
      <el-table-column label="排名" align="center" prop="ranking" />
      <!-- <el-table-column label="不及格门数" align="center" prop="nopass" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comprehensive:ranking:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comprehensive:ranking:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改平均学分绩总排名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="stuNo">
          <el-input v-model="form.stuNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入班级id" />
        </el-form-item>
        <el-form-item label="班级编号" prop="classCode">
          <el-input v-model="form.classCode" placeholder="请输入班级编号" />
        </el-form-item>
        <el-form-item label="学年id" prop="stuYearId">
          <el-input v-model="form.stuYearId" placeholder="请输入学年id" />
        </el-form-item>
        <el-form-item label="所选课程总学分" prop="courseCredit">
          <el-input v-model="form.courseCredit" placeholder="请输入所选课程总学分" />
        </el-form-item>
        <el-form-item label="所得总学分" prop="totalCredit">
          <el-input v-model="form.totalCredit" placeholder="请输入所得总学分" />
        </el-form-item>
        <el-form-item label="总成绩" prop="totalScore">
          <el-input v-model="form.totalScore" placeholder="请输入总成绩" />
        </el-form-item>
        <el-form-item label="课程数" prop="courseNum">
          <el-input v-model="form.courseNum" placeholder="请输入课程数" />
        </el-form-item>
        <el-form-item label="平均分" prop="avgScore">
          <el-input v-model="form.avgScore" placeholder="请输入平均分" />
        </el-form-item>
        <el-form-item label="平均学分绩点" prop="avgCredit">
          <el-input v-model="form.avgCredit" placeholder="请输入平均学分绩点" />
        </el-form-item>
        <el-form-item label="排名" prop="ranking">
          <el-input v-model="form.ranking" placeholder="请输入排名" />
        </el-form-item>
        <el-form-item label="不及格门数" prop="nopass">
          <el-input v-model="form.nopass" placeholder="请输入不及格门数" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createDate">
          <el-date-picker clearable v-model="form.createDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateDate">
          <el-date-picker clearable v-model="form.updateDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择修改时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRanking, getRanking, delRanking, addRanking, updateRanking, doImport } from "@/api/stuCQS/basedata/ranking";
import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, file2Xce } from "@/api/helpFunc";
import { isEmpty, fullLoading } from "@/api/helpFunc";

export default {
  name: "Ranking",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平均学分绩总排名表格数据
      rankingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuNo: null,
        classId: null,
        classCode: null,
        stuYearId: null,
        courseCredit: null,
        totalCredit: null,
        totalScore: null,
        courseNum: null,
        avgScore: null,
        avgCredit: null,
        ranking: null,
        nopass: null,
        status: null,
        createDate: null,
        updateDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      uploadV: false,
      fileList: [],
      tableData: [],
      currentPage: 1,
      pagesize: 10,
      total: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async doImport() {
      let sdata = [...this.tableData];
      let loading = fullLoading(this);
      let res = await doImport(sdata);
      loading.close();
      if (res.code == 200) {
        this.$message.success(res.msg)
      }
      this.getList();
    },

    // 下载申请信息模板
    downloadMode() {
      // 第一个sheet工作簿，如果需要创建多个，对应let多个sheetXdata即可
      let sheet1data = [
        {
          stuNo: "20210001",
          test_score: 95,
          "操作提示": "第一条为样板数据，stuNo表示学号，test_score表示学生的体能测试成绩"
        },
      ];
      // let sheet2data = []; // 第二个sheet工作簿
      // 转换sheet格式
      var sheet1 = XLSX.utils.json_to_sheet(sheet1data);
      // 创建一个新的空的workbook      
      var wb = XLSX.utils.book_new();
      // 为每一个工作簿设置名称并添加到workbook（excel表）中
      XLSX.utils.book_append_sheet(wb, sheet1, "体能测试分导入模板");
      const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
      // 下载文档并添加文件名称
      openDownloadDialog(workbookBlob, "体能测试分导入模板.xlsx");  // 辅助函数openDownloadDialog
    },
    async fileChoose(file, fileList) {
      let data = await this.handleData(file);
      let finalData = [];
      data.map(x => {
        if (!isEmpty(x["学号"])) {
          let temp = {
            stuNo: x["学号"],
            avgCredit: x["平均学分绩"],
            ranking: x["排名"]
          };
          finalData.push(temp);
        }
      });
      console.log(238, finalData);
      this.tableData = [...finalData];
      this.total = finalData.length;
    },
    handleData(file) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(file.raw);
      return new Promise((resolve, reject) => {
        reader.onload = (e) => {
          let data = e.target.result;
          let workbook = XLSX.read(data, {
            type: 'binary'
          });
          console.log(251, workbook);
          //获取json格式的Excel数据

          let total = [];
          workbook.SheetNames.map(x => {
            let temp = XLSX.utils.sheet_to_json(workbook.Sheets[x], {
              defval: 'null' //单元格为空时的默认值
            });
            total = total.concat(temp);
          });
          resolve(total);
        };
      })
    },
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    uploadVClick() {
      this.uploadV = true;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        this.excelData = [];
        this.fileList = [];
        done();
      }).catch(_ => { });
    },

    /** 查询平均学分绩总排名列表 */
    getList() {
      this.loading = true;
      listRanking(this.queryParams).then(response => {
        this.rankingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuNo: null,
        classId: null,
        classCode: null,
        stuYearId: null,
        courseCredit: null,
        totalCredit: null,
        totalScore: null,
        courseNum: null,
        avgScore: null,
        avgCredit: null,
        ranking: null,
        nopass: null,
        status: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平均学分绩总排名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRanking(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改平均学分绩总排名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRanking(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRanking(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平均学分绩总排名编号为"' + ids + '"的数据项？').then(function () {
        return delRanking(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('comprehensive/ranking/export', {
        ...this.queryParams
      }, `ranking_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
